//
//  UserInfoVC.m
//  MyProject
//
//  Created by jiaming yan on 2018/3/14.
//  Copyright © 2018年 yanjiaming. All rights reserved.
//

#import "UserInfoVC.h"
#import "ModifyPhoneVC.h"
#import <QiniuSDK.h>
#import "ModifyNickNameVC.h"
#import "UserModel.h"
#import "NSUDManager.h"

@interface UserInfoVC ()<UIActionSheetDelegate,UINavigationControllerDelegate, UIImagePickerControllerDelegate>
@property (weak, nonatomic) IBOutlet UIImageView *headImageView;
@property (weak, nonatomic) IBOutlet UILabel *nickNameLabel;
@property (weak, nonatomic) IBOutlet UILabel *phoneLabel;

@end

@implementation UserInfoVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.navigationItem.title = @"个人信息";

    
//    [self showProgressWithView:self.view animated:YES];
    UserModel *user = [NSUDManager currentUser];
    [self.headImageView sd_setImageWithURL:[NSURL URLWithString:ImageURL(user.headImg)] placeholderImage:IMAGE(@"默认图")];
    self.nickNameLabel.text = user.nickName;
    self.phoneLabel.text = user.mobile;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (IBAction)nickNameClick:(id)sender {
    __weak typeof(self) weakSelf = self;
    ModifyNickNameVC *vc = [[ModifyNickNameVC alloc]init];
    vc.strName = self.nickNameLabel.text;
    vc.modifyNickName = ^(NSString *name) {
        weakSelf.nickNameLabel.text = name;
        [weakSelf showProgressWithView:self.view animated:YES];
        [YJMSendRequest updateUserInfoWithHeadImg:@"" nickName:name result:^(NSDictionary *result, NSError *error) {
            [weakSelf hideProgress:self.view animated:YES];
            result = [CommonUtils decryptDicWithResult:result];
            if([result[@"result"] integerValue] == 1)
            {
                UserModel *user = [NSUDManager currentUser];
                user.nickName = name;
                [NSUDManager setCurrentUser:user];
                
            }else{
                [CommonUtils showToast:[result objectForKey:@"msg"]];
            }
        }];
    };
    vc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:vc animated:YES];
}
- (IBAction)modifyPhoneClick:(id)sender {
    ModifyPhoneVC *vc = [[ModifyPhoneVC alloc]init];
    vc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:vc animated:YES];
}
- (IBAction)headButtonClick:(id)sender {
    UIActionSheet *sheet = [[UIActionSheet alloc]initWithTitle:@"请选择图片" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:@"拍摄" otherButtonTitles:@"从相册选择", nil];
    [sheet showInView:self.view];
    [self.view endEditing:YES];
}
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    
    if (buttonIndex == 0) {
        //拍摄
        //先设定sourceType为相机，然后判断相机是否可用（ipod）没相机，不可用将sourceType设定为相片库
        UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
        if (![UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]) {
            sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        }
        sourceType = UIImagePickerControllerSourceTypeCamera; //照相机
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];//初始化
        picker.view.tag = actionSheet.tag;
        picker.delegate = self;
        picker.allowsEditing = YES;//设置可编辑
        picker.sourceType = sourceType;
        [self presentViewController:picker animated:YES completion:nil];
        
    }else if (buttonIndex == 1) {
        //从相册选择
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        picker.delegate = self;
        picker.allowsEditing = YES;//设置可编辑
        picker.view.tag = actionSheet.tag;
        [self presentViewController:picker animated:YES completion:nil];
    }
}


-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [self dismissViewControllerAnimated:YES completion:nil];
}



- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)aImage editingInfo:(NSDictionary *)editingInfo
{
    
    [picker dismissViewControllerAnimated:YES completion:nil];
    // 获得编辑过的图片
    // 把图片转成NSData类型的数据来保存文件(存入到沙盒中)
    // 判断图片是不是png格式的文件
    NSData *imageData = UIImageJPEGRepresentation(aImage, 1.0);
    
    if (UIImagePNGRepresentation(aImage)) {
        // 返回为png图像。
    }else if (imageData){
        // 返回为JPEG图像
    }else{
        [[CommonUtils sharedCommonUtils]showAlert:@"请上传 jpeg或是png格式" delegate:nil];
        return;
    }
    __weak typeof(self) weakSelf = self;
    [self showProgressWithView:self.view animated:YES];
    [YJMSendRequest postDataWithParameters:@{} url:@"common/getQiuNiuUpToken" result:^(NSDictionary *result, NSError *error) {
        result = [CommonUtils decryptDicWithResult:result];
        [self hideProgress:self.view animated:YES];
        if([result[@"result"] integerValue] == 1)
        {
            NSString *token = result[@"data"][@"upToken"];
            //华北
            QNConfiguration *config = [QNConfiguration build:^(QNConfigurationBuilder *builder) {
                builder.zone = [QNFixedZone zone1];
            }];
            QNUploadManager *upManager = [[QNUploadManager alloc] initWithConfiguration:config];
            [upManager putData:imageData key:nil token:token complete: ^(QNResponseInfo *info, NSString *key, NSDictionary *resp) {
                                weakSelf.headImageView.image = aImage;
                [YJMSendRequest updateUserInfoWithHeadImg:resp[@"key"] nickName:@"" result:^(NSDictionary *result, NSError *error) {
                    [weakSelf hideProgress:self.view animated:YES];
                    result = [CommonUtils decryptDicWithResult:result];
                    if([result[@"result"] integerValue] == 1)
                    {
                        UserModel *user = [NSUDManager currentUser];
                        user.headImg = resp[@"key"];
                        [NSUDManager setCurrentUser:user];
                        
                    }else{
                        [CommonUtils showToast:[result objectForKey:@"msg"]];
                    }
                }];
                
            } option:nil];
            
        }else{
            
            
            [CommonUtils showToast:[result objectForKey:@"msg"]];
        }
        
    }];
    

}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
